<?php

namespace App\Http\Controllers\Api;

use App\Models\Role;
use App\Models\UserRole;
use App\Transformers\RoleTransformer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class RolesController extends Controller
{
    public function index()
    {
        $roles = Role::all();

        return $this->response->collection($roles, new RoleTransformer());
    }

    public function add(Request $request)
    {
        $user_id = $request->input('user_id');
        $roles = $request->input('checkRoleList');

        DB::transaction(function () use($user_id, $roles) {
            DB::table('user_role')->where('user_id', $user_id)
                ->delete();
            $arr = [];
            foreach ($roles as $role) {
                $arr[] = ['user_id' => $user_id, 'role_id' => Role::ROLES_ID[$role]];
            }
            DB::table('user_role')->insert($arr);
        });

        return $this->response->created();
    }
}
